# -*- coding: utf-8 -*-
import redis, time
import redis_lock as redisLock
from openerp.osv import osv
from openerp.http import get_redis_parmas
redis_params = get_redis_parmas()
redis_instance = redis.Redis(host=redis_params.get('redis_host', 'localhost'),
                             port=int(redis_params.get('redis_port', '6379')),
                             db=int(redis_params.get('redis_decorate_db', '2')),
                             password=redis_params.get("redis_password", ''))


def redis_lock(blocking=True, error_str="请稍后重试!", blocking_timeout=3, timeout=60):
    """
    :param blocking:  当锁存在时，是否等待解锁。
    :param error_str: 当阻塞时间超过 blocking_timeout 就会报错提示，提示信息 为error
    :param blocking_timeout: 锁存在时，阻塞时间。
    :param timeout:  锁过期时间。万一程序内部出现错误，没法正常解锁，或者程序内部卡住了就自动解锁。
    :return:
    """
    def decorator(func):
        def wrapper(self, *args, **kwargs):
            purchase_need_refresh_lock = redisLock.Lock(redis_instance, "%s_%s" % (self._table, func.func_name), expire=timeout)
            if purchase_need_refresh_lock.acquire(blocking=blocking, timeout=blocking_timeout):
                # 阻塞 3秒 过时报错 默认是3秒
                try:
                    func_return = func(self, *args, **kwargs)
                except Exception as error:
                    raise error
                finally:
                    purchase_need_refresh_lock.release()
            else:
                raise osv.except_osv(u'错误！', error_str)
            return func_return
        return wrapper
    return decorator
